package cn.zhxu.toys.oss;

import com.obs.services.ObsClient;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.ObsObject;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class HuaweiOssManager extends AbstractOssManager implements InitializingBean, DisposableBean {

    private String accessKey;
    private String secretKey;
    private String bucketName;

    private ObsClient obsClient;

    @Override
    public void afterPropertiesSet() {
        obsClient = new ObsClient(accessKey, secretKey, endpoint);
    }

    @Override
    public String upload(String fileName, String key, String contentType, String extension, InputStream inputStream) {
        try {
            long fileSize = inputStream.available();
            if(fileSize > maxSize) {
                inputStream.close();
                throw new RuntimeException("上传的文件过大：" + fileSize + "，最大只允许：" + maxSize);
            }
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength((long) inputStream.available());
            metadata.setCacheControl("no-cache");
            metadata.setContentEncoding("utf-8");
            if (fileName == null) {
                fileName = System.currentTimeMillis()
                        + new Random().nextInt() + extension;
            } else {
                fileName += extension;
            }
            if (contentType != null) {
                metadata.setContentType(contentType);
            }
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            if (!key.endsWith("/")) {
                key += "/";
            }
            String fileKey = key + fileName;
            obsClient.putObject(bucketName, fileKey, inputStream, metadata);
            return resolveFileAccessUrl(fileKey);
        } catch (Exception e) {
            throw new RuntimeException("上传出现异常：", e);
        }
    }

    @Override
    public InputStream access(String key) {
        ObsObject object = obsClient.getObject(bucketName, key);
        return object.getObjectContent();
    }

    @Override
    public boolean delete(String fileUrl) {
        String fileKey = resolveFileKey(fileUrl);
        if (fileKey != null) {
            try {
                String decodedKey = URLDecoder.decode(fileKey, StandardCharsets.UTF_8.name());
                obsClient.deleteObject(bucketName, decodedKey);
                return true;
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    @Override
    protected String getBaseAccessUrl(String protocol, String host) {
        return protocol + bucketName + "." + host + "/";
    }

    @Override
    public void destroy() throws Exception {
        if (obsClient != null) {
            obsClient.close();
        }
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

}
